import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter/widgets.dart';
import 'package:flutter_aliplayer/flutter_aliplayer.dart';
import 'package:flutter_aliplayer/flutter_aliplayer_factory.dart';
import 'package:get/get.dart';
import 'package:logger/logger.dart';
import 'package:ball_lion/entity/live/live_detail_entity.dart';
import 'package:ball_lion/resources/colours.dart';
import 'package:ball_lion/routes/routes.dart';
import 'package:ball_lion/utils/utils.dart';
import 'package:ball_lion/widgets/circular.dart';

class LiveFloatController extends GetxController {
  static final LiveFloatController instance = Get.find<LiveFloatController>();

  FlutterAliplayer _player =
      FlutterAliPlayerFactory.createAliPlayer(playerId: "88");
  LiveDetailEntity? currentInfo;

  bool offStage = true;
  double top = 150;
  double right = 0;
  double _width = Get.width * 0.3;
  double _height = Get.height * 0.3;
  Offset? offset;
  int? viewId;
  AppLifecycleListener? _lifecycleListener;

  double get height => _height;
  set height(double value) {
    _height = value;
    update();
  }

  double get width => _width;
  set width(double value) {
    _width = value;
    update();
  }

  @override
  void onInit() {
    init();
    super.onInit();
  }

  Future init() async {
    FlutterAliPlayerFactory.loadRtsLibrary();
    await _player.setScalingMode(FlutterAvpdef.AVP_SCALINGMODE_SCALETOFILL);
    // await _player.setAutoPlay(true);
    _player.setOnError((errorCode, errorExtra, errorMsg, playerId) {
      Logger().d(errorMsg);
    });
    _player.setOnPrepared((playerId) {
      Logger().d(playerId);
      _player.play();
    });
    _player.setOnRenderingStart((playerId) {
      Logger().d(playerId);
    });
    _player.setOnStateChanged((newState, playerId) {
      Logger().d(newState);
    });
    _player
        .setOnVideoSizeChanged((videoWidth, videoHeight, rotation, playerId) {
      if (videoWidth * 0.2 <= Get.width / 2) {
        width = videoWidth * 0.2;
        height = videoHeight * 0.2;
      } else {
        width = Get.width / 2;
        height = (Get.width / 2) * videoHeight / videoWidth;
      }
    });
  }

  void create(int id) {
    viewId = id;
    _player.setPlayerView(viewId!);
  }

  void prepare(LiveDetailEntity? info) async {
    await clear();
    currentInfo = info;
    if (currentInfo?.bindMatch == 1) {
      width = Get.width * 0.4;
      height = 199 * 0.4;
    }
    update();
  }

  void show() {
    if ((currentInfo?.url?.contains("artc") ?? false) &&
        (currentInfo?.url.hasValue ?? false) &&
        Get.mediaQuery.orientation != Orientation.landscape) {
      offStage = false;
      _player.setUrl(currentInfo?.url ?? "");
      _player.prepare();
      try {
        _lifecycleListener = AppLifecycleListener(
          onResume: () => _player.setMuted(false),
          onHide: () => _player.setMuted(true),
        );
      } catch (e) {
        Logger().d(e);
      }
      update();
    }
  }

  Future off() async {
    offStage = true;
    offset = null;
    await _player.clearScreen();
    await _player.destroy();
    _player = FlutterAliPlayerFactory.createAliPlayer(playerId: "88");
    init();
    _player.setPlayerView(viewId ?? 0);
    try {
      _lifecycleListener?.dispose();
    } catch (e) {
      Logger().d(e);
    }
    update();
  }

  Future clear() async {
    currentInfo = null;
    await off();
  }

  void toPage() {
    if (currentInfo?.bindMatch == 1) {
      var cRoute = Get.currentRoute;
      String beforeeRoute = Get.previousRoute;
      if (beforeeRoute.contains(Routes.zqMatchDetail) ||
          beforeeRoute.contains(Routes.lqMatchDetail)) {
        Get.back();
      } else if (cRoute == '/navigation') {
        Get.toNamed(
            currentInfo?.sportsId == 1
                ? Routes.zqMatchDetail
                : Routes.lqMatchDetail,
            arguments: currentInfo?.matchId,
            parameters: {"roomId": "${currentInfo?.liveId}"});
      } else {}
    } else {
      Get.toNamed(Routes.liveNormal, arguments: currentInfo?.liveId);
    }
  }
}

class LiveFloatWidget extends StatefulWidget {
  const LiveFloatWidget({super.key});

  @override
  State<LiveFloatWidget> createState() => _LiveFloatWidgetState();
}

class _LiveFloatWidgetState extends State<LiveFloatWidget> {
  LiveFloatController controller = Get.put(LiveFloatController());

  @override
  Widget build(BuildContext context) {
    return GetBuilder<LiveFloatController>(builder: (controller) {
      return Stack(
        children: [
          AnimatedPositioned(
              right: controller.right,
              top: controller.top,
              duration: const Duration(milliseconds: 150),
              child: Offstage(
                offstage: controller.offStage,
                child: GestureDetector(
                    onPanUpdate: (details) {
                      controller.top = controller.top + details.delta.dy;
                      controller.right = controller.right - details.delta.dx;
                      setState(() {});
                    },
                    onPanEnd: (details) {
                      if (controller.right != 0.0 &&
                          controller.right != Get.width) {
                        if (controller.right + controller.width / 2 >
                            Get.width / 2) {
                          controller.right = Get.width - controller.width - 4;
                        } else {
                          controller.right = 4;
                        }
                        setState(() {});
                      }
                    },
                    child: Stack(
                      children: [
                        Circular(
                          width: controller.width,
                          height: controller.height,
                          color: Colours.black,
                          radius: 8,
                          clipBehavior: Clip.antiAlias,
                          child: Listener(
                            onPointerDown: (details) {
                              controller.offset = details.position;
                            },
                            onPointerUp: (details) {
                              if (details.position == controller.offset) {
                                controller.toPage();
                              }
                            },
                            child: AliPlayerView(
                              onCreated: controller.create,
                              x: 0,
                              y: 0,
                              width: controller.width,
                              height: controller.height,
                              aliPlayerViewType:
                                  AliPlayerViewTypeForAndroid.textureview,
                            ),
                          ),
                        ),
                        Positioned(
                            right: 0,
                            bottom: 0,
                            child: GestureDetector(
                              behavior: HitTestBehavior.opaque,
                              onTap: controller.off,
                              child: Container(
                                margin: const EdgeInsets.only(
                                    left: 14, top: 14, right: 4),
                                padding: const EdgeInsets.all(4),
                                child: Image.asset(
                                    Utils.getImgPath("close_42_shadow.png"),
                                    width: 14,
                                    height: 14),
                              ),
                            ))
                      ],
                    )),
              )),
        ],
      );
    });
  }
}
